package com.rpc.demo;

import com.rpc.demo.pojo.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpClient {
	public String post(String hostname,int port,Invocation invocation){
		//1.进行连接
		try {
			URL url = new URL("http", hostname, port, "/client");
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoOutput(true);//必须填

			//发送调用信息
			OutputStream os = urlConnection.getOutputStream();
			ObjectOutputStream objectOutput = new ObjectOutputStream(os);
			objectOutput.writeObject(invocation);
			objectOutput.flush();
			objectOutput.close();

			//将输入流转为字符串（此处可是java对象) 获取远程调用的结果
			InputStream inputStream = urlConnection.getInputStream();
			return IOUtils.toString(inputStream);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
